<template>
  <div>   
    <el-table :data="kvm.comInfos"  @row-click='handleCurrentChanges' style="width: 100%"  highlight-current-row>      
      <el-table-column
        :label="$t('message.kvms.mode')"
        prop="comCfg.mode">
      </el-table-column>
      <el-table-column
        :label="$t('message.kvms.baudRate')"
        prop="comCfg.baudRate">
      </el-table-column>
      <el-table-column
        :label="$t('message.kvms.parity')"
        prop="comCfg.parity">
      </el-table-column>
      <el-table-column
        :label="$t('message.kvms.dataBits')"
        prop="comCfg.dataBits">
      </el-table-column>
      <el-table-column
        :label="$t('message.kvms.stopBits')"
        prop="comCfg.stopBits">
      </el-table-column>
      <el-table-column :label="$t('message.kvms.txEn')">
        <template slot-scope="scope">{{scope.row.comCfg.txEn?$t('message.yes'):$t('message.no')}}</template>
      </el-table-column>
      <el-table-column :label="$t('message.kvms.rxEn')">
        <template slot-scope="scope">{{scope.row.comCfg.rxEn?$t('message.yes'):$t('message.no')}}</template>
      </el-table-column>
      <el-table-column
        :label="$t('message.kvms.rxFormat')"
        prop="comCfg.rxFormat">
      </el-table-column>
    </el-table> 
    <setForm  v-show="show">       
       <template slot="boxTop">{{$t('message.kvms.comConfig')}}</template>
          <template slot="boxMain">                
           <el-row>
            <el-col :span="4" class="col4net">       
              <div class="span3" v-for="item in labels" :key="item">  
                <label>{{$t('message.kvms.'+item)}}</label>    
              </div>                                                           
            </el-col>
            <el-col :span="20" class="col20">
              <div class="span17">                
                <el-select v-model="currenRow.mode">
                  <el-option v-for="option in comPro.modeSupport" :key="option" :value="option">{{option}}</el-option>
                </el-select>
              </div>  
              <div class="span17">                
                <el-select v-model="currenRow.baudRate">
                  <el-option v-for="option in comPro.baudRateSupport" :key="option" :value="option">{{option}}</el-option>
                </el-select>
              </div>  
              <div class="span17">                
                <el-select v-model="currenRow.parity">
                  <el-option v-for="option in comPro.paritySupport" :key="option" :value="option">{{option}}</el-option>
                </el-select>
              </div>  
              <div class="span17">                
                <el-select v-model="currenRow.dataBits">
                  <el-option v-for="option in comPro.dataBitsSupport" :key="option" :value="option">{{option}}</el-option>
                </el-select>
              </div>  
              <div class="span17">                
                <el-select v-model="currenRow.stopBits">
                  <el-option v-for="option in comPro.stopBitsSupport" :key="option" :value="option">{{option}}</el-option>
                </el-select>
              </div>  
              <div class="span17">                
                <el-select v-model="currenRow.rxFormat">
                  <el-option v-for="option in comPro.txFormatSupport" :key="option" :value="option">{{option}}</el-option>
                </el-select>
              </div>  
               <div class="span17">
                <el-switch v-model="currenRow.txEn"></el-switch>
              </div>  
              <div class="span17">
                 <el-switch v-model="currenRow.rxEn"></el-switch>               
              </div>  
            </el-col>
          </el-row>                           
          <el-button  class="btnsave" @click="onSaveComCfg">{{$t('message.save')}}</el-button>
          </template>  
    </setForm>
    <setForm  v-show="show">       
       <template slot="boxTop">{{$t('message.kvms.comTx')}}</template>
          <template slot="boxMain">                
           <el-row>
            <el-col :span="4" class="col4net">       
              <div class="span3" v-for="item in txLabels" :key="item">  
                <label>{{$t('message.kvms.'+item)}}</label>    
              </div>                                                           
            </el-col>
            <el-col :span="20" class="col20">
              <div class="span17">
                <select v-model="txCfg.format"  >
                  <option v-for="option in comPro.txFormatSupport" :key="option">{{option}}</option>
                </select>           
              </div>               
              <div class="span17">
                <el-input v-model="txCfg.payload"></el-input>  
                <span v-show="hasUnvalidateTxpayload" class="text-style" > {{$t('message.kvms.hex8FmtErr') }} </span>                  
              </div>               
            </el-col>
          </el-row>                           
          <el-button  class="btnsave" @click="onComTx">{{$t('message.send')}}</el-button>
          </template>   
    </setForm>
    <setForm  v-show="show">       
       <template slot="boxTop">{{$t('message.kvms.comRx')}}</template>
          <template slot="boxMain">  
            <el-row>
              <el-col :span="4" class="col4net">   
                 <label>{{$t('message.kvms.rxData')}}</label>                
              </el-col>
              <el-col :span="20" class="col20">
                <textarea v-model="rxCfg.payload" readonly style="width:540px;height:300px;"></textarea><br>      
                <el-button v-if="showBtnSub" class="btnsave" @click="onSUbComRx">{{$t('message.sub')}}</el-button>
                <el-button v-else class="btnsave" @click="onUnSubComRx">{{$t('message.unSub')}}</el-button>    
              </el-col>
            </el-row>     
            
          </template>   
    </setForm>
  </div>
</template>

<script>
import { api } from "../../../../libs/api";
import setForm from "@/components/setForm";
import ebus from "../../../../libs/ebus";
import { mapState, mapActions } from "vuex";

const Hex8_Reg = /^([0-9a-fA-f]{2})*$/; //检验HEX8的正则表达式 2位2位地读，重复0~n次
const Hex16_Reg = /^([0-9a-fA-f]{4})*$/; 
const Hex32_Reg = /^([0-9a-fA-f]{8})*$/; 

export default {
  created() {
    this.loadData();
    this.onSUbComRx();
  },
  beforeDestroy(){
    this.onUnSubComRx();
  },
  computed: {
    ...mapState(["kvm"]),
    hasUnvalidateTxpayload(){
      var payload = this.txCfg.payload.replace(/\s+/g,"");
      if(this.txCfg.format.toUpperCase() == 'HEX8'){
        return !Hex8_Reg.test(payload);
      } else if(this.txCfg.format.toUpperCase() == 'HEX16'){
        return !Hex16_Reg.test(payload);
      } else if(this.txCfg.format.toUpperCase() == 'HEX32'){
        return !Hex32_Reg.test(payload);
      } else{
        return false;
      }
    }
  },
  data() {
    return {
      showBtnSub: false,
      index: 0,
      currenRow: {},
      comPro: [],
      tableData: [],
      show: false,
      labels: [
        "mode",
        "baudRate",
        "parity",
        "dataBits",
        "stopBits",
        "rxFormat",
        "txEn",
        "rxEn"
      ],
      txLabels: ["txFormat", "payload"],
      txCfg: {
        format: "hex8",
        payload: ""
      },
      rxCfg: {
        format: "",
        payload: ""
      }
     
    };
  },
  components: {
    setForm
  },
  methods: {
    loadData() {
      ebus.emit("getCCInfo", this);
    },
    handleCurrentChanges(val) {
      this.currenRow = val.comCfg;
      this.comPro = val.comPro;
      this.show = true;
      this.index = val.index;
    },
    onSaveComCfg() {
      var req = this.currenRow;
      req.baudRate = parseInt(req.baudRate);
      req.dataBits = parseInt(req.dataBits);
      this.onSendRequest("$method.$set.ccInf.port.com" + this.index + ".cfg", req);
    },
    onComTx() {
      if(this.hasUnvalidateTxpayload){
        return;
      }
      this.txCfg.payload = this.txCfg.payload.replace(/\s+/g,"");
      api.Publish(`$dstream.ccInf.port.com${this.index}.tx`, JSON.stringify(this.txCfg), (msg) =>{
        console.log('COM report: ', msg)
        var res = JSON.parse(msg);
        if (res.code == 0) {
          this.notification("Success", "");
        } else {
          this.showCodeMsg(res.code, this, res.msg);
        }
      })
    },
    onSendRequest(uri, req) {
      api.onRequest(uri, JSON.stringify(req), null, null, function(message, reqReply) {
          var res = JSON.parse(message);
          if (res.code == 0) {
            this.loadData();
            this.notification("Success", "");
          } else {
            this.showCodeMsg(res.code, this, res.msg);
          }
        }.bind(this)
      );
    },
    onSUbComRx(){
      api.onSubscribe(`$dstream.ccInf.port.com${this.index}.rx`, (msg) =>{
        console.log('COM report: ', msg)
        var res = JSON.parse(msg);
        this.rxCfg.payload += new Date().toLocaleString() + ': ' +  res.payload + '\n'
      })
      this.showBtnSub = false;
    },
    onUnSubComRx(){
      api.onUnsubscribe(`$dstream.ccInf.port.com${this.index}.rx`)
      this.showBtnSub = true;
    },
    onTxpayloadChange(e){      
      this.txCfg.payload = this.txCfg.payload.toUpperCase();
    }
  }
};
</script>

<style scoped>

</style>

